package com.vibeplayer.app.fragment;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.vibeplayer.app.MainActivity;
import com.vibeplayer.app.R;
import com.vibeplayer.app.activity.LyricEditorActivity;
import com.vibeplayer.app.model.Song;
import com.vibeplayer.app.service.MusicPlayerService;
import com.vibeplayer.app.util.LrcParser;
import com.vibeplayer.app.util.MediaScanner;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class NowPlayingFragment extends DialogFragment {

    private ImageView imgAlbumArt;
    private TextView txtSongTitle;
    private TextView txtArtist;
    private TextView txtAlbum;
    private SeekBar seekBar;
    private TextView txtCurrentTime;
    private TextView txtTotalTime;
    private ImageView btnPlayPause;
    private ImageView btnPrevious;
    private ImageView btnNext;
    private ImageView btnClose;
    private TextView txtLyrics;
    private TextView txtPreviousLyric;
    private TextView txtNextLyric;
    private View lyricsContainer;
    private ImageView btnEditLyrics;

    private MusicPlayerService musicService;
    private boolean isBound = false;
    private Timer timer;
    private Handler handler;
    private MediaScanner mediaScanner;
    private LrcParser lrcParser;

    public static NowPlayingFragment newInstance() {
        return new NowPlayingFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle);
        handler = new Handler(Looper.getMainLooper());
        mediaScanner = new MediaScanner(requireContext());
        lrcParser = new LrcParser();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_now_playing, container, false);
        
        // 初始化控件
        imgAlbumArt = view.findViewById(R.id.imgAlbumArtLarge);
        txtSongTitle = view.findViewById(R.id.txtSongTitleLarge);
        txtArtist = view.findViewById(R.id.txtArtistLarge);
        txtAlbum = view.findViewById(R.id.txtAlbumLarge);
        seekBar = view.findViewById(R.id.seekBarLarge);
        txtCurrentTime = view.findViewById(R.id.txtCurrentTimeLarge);
        txtTotalTime = view.findViewById(R.id.txtTotalTimeLarge);
        btnPlayPause = view.findViewById(R.id.btnPlayPauseLarge);
        btnPrevious = view.findViewById(R.id.btnPreviousLarge);
        btnNext = view.findViewById(R.id.btnNextLarge);
        btnClose = view.findViewById(R.id.btnClose);
        txtLyrics = view.findViewById(R.id.txtLyrics);
        txtPreviousLyric = view.findViewById(R.id.txtPreviousLyric);
        txtNextLyric = view.findViewById(R.id.txtNextLyric);
        lyricsContainer = view.findViewById(R.id.lyricsContainer);
        btnEditLyrics = view.findViewById(R.id.btnEditLyrics);
        
        // 设置关闭按钮点击事件
        btnClose.setOnClickListener(v -> dismiss());
        
        // 获取音乐服务
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isServiceBound()) {
                musicService = activity.getMusicService();
                isBound = true;
                updateUI();
                startProgressTimer();
            }
        }
        
        // 设置控制按钮点击事件
        setupControlButtons();
        
        // 设置进度条拖动事件
        setupSeekBar();
        
        // 设置歌词编辑按钮点击事件
        btnEditLyrics.setOnClickListener(v -> {
            if (isBound && musicService != null) {
                Song currentSong = musicService.getCurrentSong();
                if (currentSong != null) {
                    Intent intent = new Intent(getActivity(), LyricEditorActivity.class);
                    intent.putExtra(LyricEditorActivity.EXTRA_SONG, currentSong);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), R.string.no_songs_found, Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isBound && musicService != null) {
            updateUI();
            startProgressTimer();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        stopProgressTimer();
    }

    private void setupControlButtons() {
        // 播放/暂停按钮点击事件
        btnPlayPause.setOnClickListener(v -> {
            if (isBound && musicService != null) {
                musicService.playPause();
                updatePlayPauseButton();
            }
        });
        
        // 上一曲按钮点击事件
        btnPrevious.setOnClickListener(v -> {
            if (isBound && musicService != null) {
                musicService.playPrevious();
            }
        });
        
        // 下一曲按钮点击事件
        btnNext.setOnClickListener(v -> {
            if (isBound && musicService != null) {
                musicService.playNext();
            }
        });
    }

    private void setupSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && isBound && musicService != null) {
                    musicService.seekTo(progress);
                    updateCurrentTimeText(progress);
                    updateLyrics(progress);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void updateUI() {
        if (!isBound || musicService == null) {
            return;
        }
        
        Song currentSong = musicService.getCurrentSong();
        if (currentSong != null) {
            txtSongTitle.setText(currentSong.getTitle());
            txtArtist.setText(currentSong.getArtist());
            txtAlbum.setText(currentSong.getAlbum());
            
            // 加载专辑封面
            Uri albumArtUri = mediaScanner.getAlbumArtUri(currentSong.getAlbumId());
            try {
                imgAlbumArt.setImageURI(albumArtUri);
                if (imgAlbumArt.getDrawable() == null) {
                    imgAlbumArt.setImageResource(R.drawable.default_album_art);
                }
            } catch (Exception e) {
                imgAlbumArt.setImageResource(R.drawable.default_album_art);
            }
            
            // 更新播放/暂停按钮
            updatePlayPauseButton();
            
            // 更新进度条
            int duration = musicService.getDuration();
            seekBar.setMax(duration);
            txtTotalTime.setText(formatTime(duration));
            updateSeekBar();
            
            // 加载歌词
            loadLyrics(currentSong);
        }
    }

    private void updatePlayPauseButton() {
        if (isBound && musicService != null && musicService.isPlaying()) {
            btnPlayPause.setImageResource(R.drawable.ic_pause);
        } else {
            btnPlayPause.setImageResource(R.drawable.ic_play);
        }
    }

    private void updateSeekBar() {
        if (isBound && musicService != null && musicService.isPrepared()) {
            int currentPosition = musicService.getCurrentPosition();
            seekBar.setProgress(currentPosition);
            updateCurrentTimeText(currentPosition);
            updateLyrics(currentPosition);
        }
    }

    private void updateCurrentTimeText(int currentPosition) {
        txtCurrentTime.setText(formatTime(currentPosition));
    }

    private void startProgressTimer() {
        stopProgressTimer();
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                handler.post(() -> {
                    if (isBound && musicService != null && musicService.isPlaying()) {
                        updateSeekBar();
                        updatePlayPauseButton();
                    }
                });
            }
        }, 0, 1000);
    }

    private void stopProgressTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / (1000 * 60)) % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void loadLyrics(Song song) {
        // 尝试加载歌词文件
        String songPath = song.getPath();
        String lrcPath = songPath.substring(0, songPath.lastIndexOf(".")) + ".lrc";
        File lrcFile = new File(lrcPath);
        
        if (lrcFile.exists()) {
            lrcParser.loadLrc(lrcFile);
            showLyricsContainer(true);
            updateLyrics(musicService.getCurrentPosition());
            
            // 显示歌曲元数据
            String title = lrcParser.getMetadata("ti");
            String artist = lrcParser.getMetadata("ar");
            String album = lrcParser.getMetadata("al");
            
            if (title != null && !title.isEmpty()) {
                txtSongTitle.setText(title);
            }
            if (artist != null && !artist.isEmpty()) {
                txtArtist.setText(artist);
            }
            if (album != null && !album.isEmpty()) {
                txtAlbum.setText(album);
            }
        } else {
            showLyricsContainer(false);
            txtLyrics.setText("暂无歌词");
        }
    }

    private void showLyricsContainer(boolean hasLyrics) {
        if (hasLyrics) {
            lyricsContainer.setVisibility(View.VISIBLE);
        } else {
            lyricsContainer.setVisibility(View.GONE);
            txtLyrics.setVisibility(View.VISIBLE);
        }
    }

    private void updateLyrics(int currentPosition) {
        if (lrcParser.isLoaded()) {
            // 获取当前行歌词
            String currentLine = lrcParser.getLyricLine(currentPosition);
            // 获取前一行歌词
            String previousLine = lrcParser.getPreviousLyricLine(currentPosition);
            // 获取后一行歌词
            String nextLine = lrcParser.getNextLyricLine(currentPosition);
            
            // 更新歌词显示
            if (currentLine != null && !currentLine.isEmpty()) {
                // 检查歌词是否变化，如果变化则添加动画效果
                if (!currentLine.equals(txtLyrics.getText().toString())) {
                    animateLyricChange(txtLyrics, currentLine);
                    animateLyricChange(txtPreviousLyric, previousLine);
                    animateLyricChange(txtNextLyric, nextLine);
                }
            }
            
            // 获取下一行歌词的时间，用于设置定时更新
            long nextLyricTime = lrcParser.getNextLyricTime(currentPosition);
            if (nextLyricTime > 0) {
                long delay = nextLyricTime - currentPosition;
                if (delay > 0 && delay < 5000) { // 确保延迟在合理范围内
                    handler.postDelayed(this::updateLyricsWithAnimation, delay);
                }
            }
        } else {
            txtLyrics.setText("暂无歌词");
            txtPreviousLyric.setText("");
            txtNextLyric.setText("");
        }
    }
    
    private void updateLyricsWithAnimation() {
        if (isBound && musicService != null && musicService.isPlaying()) {
            updateLyrics(musicService.getCurrentPosition());
        }
    }
    
    private void animateLyricChange(TextView textView, String newText) {
        // 设置淡出动画
        ObjectAnimator fadeOut = ObjectAnimator.ofFloat(textView, "alpha", 1f, 0.3f);
        fadeOut.setDuration(200);
        fadeOut.setInterpolator(new AccelerateDecelerateInterpolator());
        
        // 设置淡入动画
        ObjectAnimator fadeIn = ObjectAnimator.ofFloat(textView, "alpha", 0.3f, 1f);
        fadeIn.setDuration(200);
        fadeIn.setInterpolator(new AccelerateDecelerateInterpolator());
        
        // 执行淡出动画
        fadeOut.start();
        
        // 更新文本并执行淡入动画
        handler.postDelayed(() -> {
            textView.setText(newText != null ? newText : "");
            fadeIn.start();
        }, 200);
    }
}